/**
 * 
 */
package net.toocruel.iqismart.service.core.impl;


import net.toocruel.iqismart.dao.UserRepository;
import net.toocruel.iqismart.dao.core.*;
import net.toocruel.iqismart.entity.common.Category;
import net.toocruel.iqismart.entity.common.Tag;
import net.toocruel.iqismart.entity.core.Authentication;
import net.toocruel.iqismart.service.core.AuthenticationService;
import net.toocruel.iqismart.service.core.CategoryService;
import net.toocruel.iqismart.service.core.TagService;
import net.toocruel.iqismart.service.dto.ProfileAuthenticationDTO;
import net.toocruel.iqismart.service.exception.BusinessException;
import net.toocruel.iqismart.utils.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindException;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;

import java.io.IOException;
import java.util.List;
import java.util.Set;

/**
 * @author toocruel
 *
 */
@Service
@Transactional
public class AuthenticationServiceImpl implements AuthenticationService {
    @Autowired
    private TagRepository tagRepository;

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private SupportRepository supportRepository;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private AnswerRepository answerRepository;

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private AuthenticationRepository authenticationRepository;

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private TagService tagService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private FileUploadUtils fileUploadUtils;

    @Override
    public List<Authentication> getRecommendAuthentication(int count) {
        return authenticationRepository.findAll(new PageRequest(0,count,new Sort(Sort.Direction.DESC,"id"))).getContent();
    }

    @Override
    public Authentication findById(Long id) {
        return authenticationRepository.findOne((root, query, cb) -> cb.equal(root.get("user"), id));
    }

    @Autowired
    private SpringValidatorAdapter validatorAdapter;
    @Override
    public void auth(Long id, ProfileAuthenticationDTO dto) {
        if(dto.getIdCardImage().isEmpty()){
            dto.setIdCardImage(null);
        }
        if(dto.getSkillImage().isEmpty()){
            dto.setSkillImage(null);
        }
        Category category = categoryService.findById(dto.getCategoryId());
        if(category==null){
            throw new BusinessException("category","分类不存在");
        }else{
            dto.setCategory(category);
        }
        Set<Tag> tags = tagService.findAndCreateIfNotExist(dto.getCategory().getId(), dto.getTagNames());
        dto.setTags(tags);

        BindException bindException = new BindException(dto, "dto");
        validatorAdapter.validate(dto,bindException);
        if(bindException.hasErrors()){
            throw BusinessException.with(bindException);
        }


        Authentication auth = authenticationRepository.findOne((root, query, cb) -> cb.equal(root.get("user"), id));
        if(auth ==null){
            auth = new Authentication();
            auth.setUser(userRepository.findById(id));
        }
        auth.setTags(tags);
        auth.setCategory(category);
        auth.setDescription(dto.getDescription());
        auth.setTitle(dto.getTitle());
        auth.setProvince(dto.getProvince());
        auth.setCity(dto.getCity());
        auth.setGender(dto.getGender());
        auth.setRealName(dto.getRealName());
        auth.setIdCard(dto.getIdCard());

        try {
            String idCardImage = fileUploadUtils.upload(dto.getIdCardImage().getInputStream(), dto.getIdCardImage().getOriginalFilename(),200,300);
            auth.setIdCardImage(idCardImage);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("idCardImage","上传失败");
        }

        try {
            String skillImage = fileUploadUtils.upload(dto.getSkillImage().getInputStream(), dto.getSkillImage().getOriginalFilename(),200,300);
            auth.setSkillImage(skillImage);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("skillImage","上传失败");
        }

        auth.setStatus(0);
        authenticationRepository.save(auth);



    }
}
